#include <QtGui>

#include "GenHighlighter.h"
#include <QTextDocument>

GenHighlighter::GenHighlighter(QTextDocument *parent)
	: QSyntaxHighlighter(parent)
{
	{
		QTextCharFormat format;
		format.setForeground(Qt::blue);
		format.setFontWeight(QFont::Bold);		
		addKeywords(QStringList() << "can" << "specify" << "is" << 
			"implements" << "contains" << "has", format);
	}
	{
		QTextCharFormat format;
		format.setForeground(Qt::red);
		format.setFontWeight(QFont::Bold);		
		addKeywords(QStringList() << "Composition" << "leafs" <<
			"and" << "composites", format);
	}
}

void GenHighlighter::addKeywords(QStringList keywords, QTextCharFormat format)
{
	foreach (QString keyword, keywords)
	{
		QString expr;
		QTextStream(&expr) << "\\b" << keyword << "\\b";

		HighlightingRule rule;
		rule.pattern = QRegExp(expr);
		rule.format = format;

		highlightingRules.append(rule);
	};
}

void GenHighlighter::highlightBlock(const QString &text)
{
	foreach (HighlightingRule rule, highlightingRules)
	{
		QRegExp& expression = rule.pattern;
		int index = expression.indexIn(text);
		while (index >= 0)
		{
			int length = expression.matchedLength();
			setFormat(index, length, rule.format);
			index = expression.indexIn(text, index + length);
		}
	}
}
